package com.trimps.steps.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hotfire.template.common.Paginator;
import com.trimps.steps.exception.SqlOperationsException;
import com.trimps.steps.pojo.Step;
import com.trimps.steps.pojo.WalkerGroup;
import com.trimps.steps.service.IStepService;
import com.trimps.steps.service.IWalkerGroupService;
import com.trimps.steps.service.IWalkerService;

@Controller
@RequestMapping(value = "step/")
public class StepController extends BaseController {
    private static final Logger logger = Logger.getLogger(StepController.class);

    @Autowired
    private IStepService stepService;
    @Autowired
    private IWalkerService walkerService;
    @Autowired
    private IWalkerGroupService walkerGroupService;

    /**
     * 
     * @param page
     * @param map   必须这样写：@RequestParam HashMap<String, String> map,否则无法映射值, jsp页面可以通过 ${map.myname }获取
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "list")
    public String list(Paginator page, 
                    @RequestParam(required=false) String realyName,
                    @RequestParam(required=false) String startTime, 
                    @RequestParam(required=false) String endTime, 
                    @RequestParam(required=false) String groupId,
                    @RequestParam(required=false) String orderby_date,
                    @RequestParam(required=false) String orderby_stepcount,
                    @RequestParam(required=false) String orderby_group,
                    @RequestParam(required=false) String sort,
                    ModelMap modelMap) {
        
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("realyName", realyName);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("groupId", groupId);
        map.put("orderby_date", orderby_date);
        map.put("orderby_stepcount", orderby_stepcount);
        map.put("orderby_group", orderby_group);
        map.put("sort", sort);
        
        String orderBy = "";
        String st = "1".equals(sort)  ? " ASC" : " DESC";
        if(StringUtils.isNotEmpty(orderby_date)) 
            orderBy = "step_date" + st;
        if(StringUtils.isNotEmpty(orderby_stepcount)) 
            orderBy += (StringUtils.isEmpty(orderBy) ? "step_count" : ", step_count") + st;
        if(StringUtils.isNotEmpty(orderby_group)) 
            orderBy +=  (StringUtils.isEmpty(orderBy) ? "mg.id" : ", mg.id") + st;
        if(StringUtils.isEmpty(orderBy))
            orderBy = "step_date "+st;
        map.put("orderBy", orderBy);
        
        if(page == null || page.getTotalItemCount() == -1){
            page = new Paginator();
            page.setShowItemCount(8);
            int userCount = stepService.getStepCount(map);
            page.setTotalItemCount(userCount);
        }
        
        List<Step> steps = stepService.getSteps(page.getStart(), page.getOffset(), map);
        List<WalkerGroup> groups = walkerGroupService.getAllWalkerGroups();
        if(getUserId() != null){
            List<WalkerGroup> ownGroups = walkerGroupService.getWalkerGroupByUserId(getUserId());
            modelMap.put("ownGroups", ownGroups);
        }
        modelMap.put("steps", steps);
        modelMap.put("groups", groups);
        modelMap.put("page", page);
        modelMap.put("map", map);
        
        return "step/steplist";
    }
    
    @ResponseBody
    @RequestMapping(value = "doDelById", method = RequestMethod.POST)
    public Map<String, Object> doDelById( @RequestParam(required=true) String stepId,
                    ModelMap modelMap) {
        int ret = stepService.delById(stepId);
        if(ret > 0)
            buildFailureMsg("删除失败！");
        return buildSuccessMsg("删除成功！");
    }
    
    @ResponseBody
    @RequestMapping(value = "doSave")
    public Map<String, Object> saveStep(@RequestParam(required=true) int groupId, 
                    @RequestParam(required=true) String realyName, 
                    @RequestParam(required=true) int stepCount, 
                    @RequestParam(required=true) String stepDate){
        if(super.getUser() == null){
            return buildFailureMsg("用户未登录！");
        }
        try {
            int stepId = stepService.saveStep(super.getUser().getId(), groupId, realyName, stepCount, stepDate);
            if(stepId <= 0){
                buildFailureMsg("保存失败！");
            }
        } catch (SqlOperationsException e) {
            return buildFailureMsg("添加失败：人员不存在或者没有权限添加其它分组人员步数信息！");
        }
        return buildSuccessMsg("保存成功！");
    }
}
